#pragma once
#include <QWidget>
#include <QVector>
#include "vertexops.h"
#include "Config.h"
#include "tileloader.h"

class MapCanvas : public QWidget
{
    Q_OBJECT
public:
    enum Tool { Select, AddPoint, AddLine, AddPolygon };
    explicit MapCanvas(QWidget *parent = nullptr);
    void setTool(Tool t) { m_tool = t; update(); }
    void exportGeoJson(const QString &fileName);
    void loadGeoJson(const QString &fileName);
    void setZoom(int);
    int zoom();
protected:
    void paintEvent(QPaintEvent *) override;
    void mousePressEvent(QMouseEvent *) override;
    void mouseMoveEvent(QMouseEvent *) override;
    void mouseReleaseEvent(QMouseEvent *) override;
private:
    Config m_cfg;                   // 配置文件
    QPointF lonLatToXy(double lon, double lat) const;
    QPointF xyToLonLat(const QPointF &xy) const;
    void drawTiles(QPainter &p);
    void  drawFeatures(QPainter &p);
    QPointF lonLatToTile(double lon, double lat, int z) const;
    void  updateTransform();                 // 更新缩放矩阵
    QPointF lonLatToScreen(const QPointF &ll) const;
    QPointF screenToLonLat(const QPointF &xy) const;
    QPointF tileToLonLat(double tx, double ty, int z) const;
private:
    Tool m_tool = Select;
    QVector<Feature> m_feats;

    bool   m_dragging = false;
    int    m_featIdx  = -1;
    int    m_vtxIdx   = -1;
    /* 方案 C 新增 */
    QPointF m_lastPos;          // 上一次鼠标位置
    QPointF m_lastDir;          // 上一次线段方向向量（单位）
    bool    m_hasLastDir = false;
    TileLoader *m_loader = nullptr;
    QNetworkAccessManager m_netMgr;
    QCache<quint64, QPixmap> m_tileCache{200};   // 200张内存缓存
    const QString m_urlTpl = "http://webst02.is.autonavi.com/appmaptile?style=6&x=%1&y=%2&z=%3";
    int m_zoom = 17;           // 默认层级
    QPointF m_centerLL;                      // 视图中心经纬度
    QTransform m_T;                          // 当前缩放平移矩阵
};
